<script setup lang="tsx">
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { QuestionnaireQuestionVO } from '#/api/config/questionnaires/questionnaire/model';

import { onMounted, ref, watch } from 'vue';

import { useAccess } from '@vben/access';
import { useVbenModal } from '@vben/common-ui';

import {
  Checkbox,
  CheckboxGroup,
  Popconfirm,
  Radio,
  RadioGroup,
  Space,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  questionnaireInfo,
  questionnaireQuestionChangeSort,
  questionnaireQuestionList,
  // questionOptionInfo,
  questionnaireQuestionRemove,
  questionnaireQuestionUpdateStatus,
} from '#/api/config/questionnaires/questionnaire';
// import { DetailsModal } from '#/components/modal';
import { TableSwitch } from '#/components/table';

import { columns } from './data';
import questionModal from './question-modal.vue';

const props = defineProps<{
  questionnaireId: number | string;
}>();

const emit = defineEmits<{ reload: [] }>();

const { hasAccessByCodes } = useAccess();
const tableTitle = ref<string>('');

const [QuestionModal, questionModalApi] = useVbenModal({
  connectedComponent: questionModal,
});

// const [TagDetailsModal, tagDetailsModalApi] = useVbenModal({
//   connectedComponent: DetailsModal,
// });

const gridOptions: VxeGridProps = {
  columns,
  height: 'auto',
  keepSource: false,
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    ajax: {
      query: async () => {
        if (!props.questionnaireId) {
          return { rows: [] };
        }

        const resp = await questionnaireInfo(props.questionnaireId);
        const questionList = await questionnaireQuestionList({
          questionnaireId: props.questionnaireId,
        });
        tableTitle.value = `${resp.name}`;
        return { rows: questionList || [] };
      },
    },
  },
  // toolbarConfig: {
  //   enabled: true,
  //   custom: true,
  //   zoom: false,
  // },
  rowConfig: {
    keyField: 'id',
    drag: true,
    isCurrent: true,
  },
  id: 'questionnaires-questionnaire-question-list',
  showOverflow: false,
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  gridOptions,
  gridEvents: {
    rowDragend: async ({ newRow, oldRow, dragPos }) => {
      console.log(
        `拖拽完成，被拖拽行：${oldRow.name} 目标行：${newRow.name} 目标位置：${dragPos}`,
      );
      const tableList = tableApi.grid.getTableData()?.tableData ?? [];
      const sortedList = tableList.map((item, index) => {
        return { id: item.id, name: item.name, sort: index + 1 };
      });
      console.log('拖拽后表格数据：', sortedList);
      await questionnaireQuestionChangeSort(sortedList as any);
      emit('reload');
    },
  },
});

watch(
  () => props.questionnaireId,
  async () => {
    await tableApi.reload();
  },
);

onMounted(async () => {
  //
});

async function handleAdd() {
  questionModalApi.setData({ questionnaireId: props.questionnaireId });
  questionModalApi.open();
}

// async function handlePreview(row: QuestionnaireQuestionVO) {
//   tagDetailsModalApi.setData(row);
//   tagDetailsModalApi.open();
// }

// async function handleEdit(row: QuestionnaireQuestionVO) {
//   questionModalApi.setData({
//     questionId: props.questionId,
//     id: row.id,
//   });
//   questionModalApi.open();
// }

async function handleDelete(row: QuestionnaireQuestionVO) {
  await questionnaireQuestionRemove([row.id]);
  await tableApi.query();
  emit('reload');
}

async function questionStatusUpdate(row: QuestionnaireQuestionVO) {
  const data = {
    id: row.id,
    status: row.status,
  };
  await questionnaireQuestionUpdateStatus(data);
  emit('reload');
}

async function handleQuestionUpdated() {
  await tableApi.query();
  emit('reload');
}
</script>

<template>
  <BasicTable :table-title="tableTitle">
    <template #toolbar-tools>
      <Space>
        <a-button
          v-access:code="['questionnaire:question:add']"
          type="primary"
          @click="handleAdd"
        >
          新增题目
        </a-button>
      </Space>
    </template>
    <template #questionName="{ row }">
      <div class="p-[5px]">
        <div>{{ row.questionName }}</div>
        <div v-if="row.options?.length > 0" class="mt-[8px] pl-[20px]">
          <div v-if="row.questionType === 1">
            <RadioGroup
              v-for="option in row.options"
              :key="option.id"
              class="flex items-center gap-2"
              :name="row.questionId"
            >
              <Radio :value="option.id">{{ option.name }}</Radio>
            </RadioGroup>
          </div>
          <div v-if="row.questionType === 2">
            <CheckboxGroup
              v-for="option in row.options"
              :key="option.id"
              class="flex items-center gap-2"
            >
              <Checkbox :value="option.id">{{ option.name }}</Checkbox>
            </CheckboxGroup>
          </div>
        </div>
      </div>
    </template>
    <template #status="{ row }">
      <TableSwitch
        v-model:value="row.status"
        :api="() => questionStatusUpdate(row)"
        :disabled="!hasAccessByCodes(['questionnaire:question:edit'])"
        @reload="tableApi.query()"
      />
    </template>
    <template #action="{ row }">
      <Space>
        <!--<ghost-button-->
        <!--  v-access:code="['questionnaire:question:query']"-->
        <!--  @click="handlePreview(row)"-->
        <!--&gt;-->
        <!--  详情-->
        <!--</ghost-button>-->
        <!--<ghost-button-->
        <!--  v-access:code="['questionnaire:question:edit']"-->
        <!--  @click="handleEdit(row)"-->
        <!--&gt;-->
        <!--  编辑-->
        <!--</ghost-button>-->
        <Popconfirm
          placement="left"
          ok-type="danger"
          title="确认删除这条题目？"
          @confirm="handleDelete(row)"
        >
          <ghost-button
            danger
            v-access:code="['questionnaire:question:remove']"
            @click.stop=""
          >
            删除
          </ghost-button>
        </Popconfirm>
      </Space>
    </template>
  </BasicTable>
  <QuestionModal @reload="handleQuestionUpdated" />
  <!--<QuestionDetailsModal :columns="questionDetailsSchema()" :api="questionInfo" />-->
</template>
